import 'package:app/model/app_config.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:uuid/uuid.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

class ChildrenEvent {
  final RxString childrenId;
  late final RxString name;
  final RxString parentId;
  final RxInt targetTimestamp;
  final RxBool isprecise;
  final RxBool whetherToTop;
  final Rx<Color> eventColor;
  final RxString imgUrl;
  final RxDouble blurRadius;
  final Rx<Color> textColor;

  static const Uuid _uuid = Uuid();

  // 私有构造函数
  ChildrenEvent._({
    required this.childrenId,
    required this.name,
    required this.parentId,
    required this.targetTimestamp,
    required this.isprecise,
    required this.whetherToTop,
    required this.eventColor,
    required this.imgUrl,
    double blurRadius = 0.0,
    Color textColor = Colors.black,
  }) : blurRadius = RxDouble(blurRadius),
       textColor = Rx<Color>(textColor);

  // 静态工厂方法
  static ChildrenEvent create({
    required String name,
    required String parentId,
    required int targetTimestamp,
    bool isprecise = false,
    bool whetherToTop = false,
    Color? eventColor,
    String imgUrl = '',
    double blurRadius = 0.0,
    Color? textColor,
  }) {
    final generatedChildrenId = _generateChildrenId();
    var c = eventColor ?? StaticAppConfig.defaultEventColor;
    var t = textColor ?? Colors.black;
    return ChildrenEvent._(
      childrenId: RxString(generatedChildrenId),
      name: RxString(name),
      parentId: RxString(parentId),
      targetTimestamp: RxInt(targetTimestamp),
      isprecise: RxBool(isprecise),
      whetherToTop: RxBool(whetherToTop),
      eventColor: Rx<Color>(c),
      imgUrl: RxString(imgUrl),
      blurRadius: blurRadius,
      textColor: t,
    );
  }

  // 生成唯一 ID 的辅助方法
  static String _generateChildrenId() {
    return _uuid.v1();
  }

  void updateChildrenEvent({
    String? name,
    int? targetTimestamp,
    bool? isprecise,
    bool? whetherToTop,
    String? parentId,
    Color? eventColor,
    String? imgUrl,
    double? blurRadius,
    Color? textColor,
  }) {
    this.name.value = name ?? this.name.value;
    this.parentId.value = parentId ?? this.parentId.value;
    this.targetTimestamp.value = targetTimestamp ?? this.targetTimestamp.value;
    this.isprecise.value = isprecise ?? this.isprecise.value;
    this.whetherToTop.value = whetherToTop ?? this.whetherToTop.value;
    this.eventColor.value = eventColor ?? this.eventColor.value;
    this.imgUrl.value = imgUrl ?? this.imgUrl.value;
    this.blurRadius.value = blurRadius ?? this.blurRadius.value;
    this.textColor.value = textColor ?? this.textColor.value;
  }

  // 转换为 JSON
  Map<String, dynamic> toJson() {
    var cachEventColor = eventColor.value;
    var cachTextColor = textColor.value;
    return {
      'childrenId': childrenId.value,
      'name': name.value,
      'parentId': parentId.value,
      'targetTimestamp': targetTimestamp.value,
      'isprecise': isprecise.value,
      'whetherToTop': whetherToTop.value,
      'eventColor': cachEventColor.toARGB32(),
      'imgUrl': imgUrl.value,
      'blurRadius': blurRadius.value,
      'textColor': cachTextColor.toARGB32(),
    };
  }

  // 从 JSON 创建对象
  static ChildrenEvent fromJson(Map<String, dynamic> json) {
    var cachEventColor = json['eventColor'];
    var cachTextColor = json['textColor'];
    if (cachEventColor != null && cachEventColor is Color) {
      cachEventColor = cachEventColor.toARGB32();
    }
    if (cachTextColor != null && cachTextColor is Color) {
      cachTextColor = cachTextColor.toARGB32();
    }
    return ChildrenEvent._(
      childrenId: RxString(json['childrenId']),
      name: RxString(json['name']),
      parentId: RxString(json['parentId']),
      targetTimestamp: RxInt(
        json['targetTimestamp'] ?? DateTime.now().microsecondsSinceEpoch,
      ),
      isprecise: RxBool(json['isprecise'] ?? false),
      whetherToTop: RxBool(json['whetherToTop'] ?? false),
      eventColor: Rx<Color>(
        Color(cachEventColor ?? StaticAppConfig.defaultEventColor),
      ),
      imgUrl: RxString(json['imgUrl'] ?? ''),
      blurRadius: json['blurRadius']?.toDouble() ?? 0,
      textColor: Color(cachTextColor ?? Colors.black.toARGB32()),
    );
  }
}

class CountdownEventClass {
  final RxString id;
  final RxString name;
  final RxList<ChildrenEvent> eventChildren;

  static const Uuid _uuid = Uuid();

  // 私有构造函数
  CountdownEventClass._({
    required this.id,
    required this.name,
    required this.eventChildren,
  });

  // 静态工厂方法
  static CountdownEventClass create({required String name}) {
    return CountdownEventClass._(
      id: RxString(_generateCountdownEventClassId()),
      name: RxString(name),
      eventChildren: RxList<ChildrenEvent>([]),
    );
  }

  // 生成唯一 ID 的辅助方法
  static String _generateCountdownEventClassId() {
    return _uuid.v4();
  }

  // 添加子事件
  void addEventChild({
    required String name,
    required int targetTimestamp,
    bool isprecise = false,
    bool whetherToTop = false,
    Color? eventColor,
    String imgUrl = "",
    double blurRadius = 0.0,
    Color? textColor,
  }) {
    eventChildren.add(
      ChildrenEvent.create(
        name: name,
        parentId: id.value,
        targetTimestamp: targetTimestamp,
        isprecise: isprecise,
        whetherToTop: whetherToTop,
        eventColor: eventColor,
        imgUrl: imgUrl,
        blurRadius: blurRadius,
        textColor: textColor,
      ),
    );
  }

  void addEventChildWithObject(ChildrenEvent event) {
    eventChildren.add(event);
  }

  CountdownEventClass addAllEvents(List<CountdownEventClass> events) {
    for (final event in events) {
      eventChildren.addAll(event.eventChildren);
    }
    return this;
  }

  void updateName(String newName) {
    name.value = newName;
  }

  void deleteEventChild(String eventChildId) {
    eventChildren.removeWhere(
      (event) => event.childrenId.value == eventChildId,
    );
  }

  //通过子事件id查找子事件
  ChildrenEvent? findEventChildById(String eventChildId) {
    try {
      return eventChildren.firstWhere(
        (event) => event.childrenId.value == eventChildId,
      );
    } catch (_) {
      return null; // 找不到时返回null
    }
  }

  // 转换为 JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id.value,
      'name': name.value,
      'eventChildren': eventChildren.map((e) => e.toJson()).toList(),
    };
  }

  // 从 JSON 创建对象
  static CountdownEventClass fromJson(Map<String, dynamic> json) {
    try {
      final eventChildren =
          (json['eventChildren'] as List)
              .map((e) => ChildrenEvent.fromJson(e as Map<String, dynamic>))
              .toList();

      return CountdownEventClass._(
        id: RxString(json['id']),
        name: RxString(json['name']),
        eventChildren: RxList<ChildrenEvent>(eventChildren),
      );
    } catch (e) {
      debugPrint('CountdownEventClass.fromJson 错误: $e');
      return CountdownEventClass._(
        id: RxString(json['id']),
        name: RxString(json['name']),
        eventChildren: RxList<ChildrenEvent>([]),
      );
    }
  }
}

class CountdownEventClassList {
  final RxList<CountdownEventClass> countdownEventList;
  static final CountdownEventClassList _instance = CountdownEventClassList._();
  static const _cacheKey = 'countdown_event_cache';
  CountdownEventClassList._() : countdownEventList = RxList([]);
  // 静态工厂方法
  static CountdownEventClassList create() {
    return _instance;
  }

  void addCountdownEventClass(String name) {
    countdownEventList.add(CountdownEventClass.create(name: name));
  }

  void deleteCountdownEventClass(String countdownEventClassId) {
    countdownEventList.removeWhere(
      (eventClass) => eventClass.id.value == countdownEventClassId,
    );
  }

  void deleteCountdownEventClassWithChildren(String countdownEventClassId) {
    final eventToDelete = findCountdownEventClassById(countdownEventClassId);
    if (eventToDelete == null) return;

    // 如果有子事件，尝试转移
    if (eventToDelete.eventChildren.isNotEmpty) {
      // 尝试找到下一个可用的父事件（优先向下查找）
      int currentIndex = countdownEventList.indexOf(eventToDelete);
      CountdownEventClass? newParent;

      // 向下查找
      for (int i = currentIndex + 1; i < countdownEventList.length; i++) {
        if (countdownEventList[i].id.value != countdownEventClassId) {
          newParent = countdownEventList[i];
          break;
        }
      }

      // 如果向下找不到，向上查找
      if (newParent == null) {
        for (int i = currentIndex - 1; i >= 0; i--) {
          if (countdownEventList[i].id.value != countdownEventClassId) {
            newParent = countdownEventList[i];
            break;
          }
        }
      }

      // 转移子事件
      if (newParent != null) {
        for (final child in eventToDelete.eventChildren) {
          child.updateChildrenEvent(
            parentId: newParent.id.value, // parentId
          );
          newParent.addEventChildWithObject(child);
        }
      }
    }

    // 删除事件
    countdownEventList.remove(eventToDelete);
  }

  // 查找方法
  CountdownEventClass? findCountdownEventClassById(String id) {
    try {
      return countdownEventList.firstWhere(
        (eventClass) => eventClass.id.value == id,
      );
    } catch (_) {
      return null; // 找不到时返回null
    }
  }

  Exception? moveEventChild(
    String eventChildId,
    String oldEventChildParentId,
    String newEventChildParentId,
  ) {
    final oldEventClass = findCountdownEventClassById(oldEventChildParentId);
    final newEventClass = findCountdownEventClassById(newEventChildParentId);
    if (oldEventClass != null && newEventClass != null) {
      final oldEventChild = oldEventClass.eventChildren.firstWhere(
        (event) => event.childrenId.value == eventChildId,
      );
      newEventClass.addEventChildWithObject(oldEventChild);
      oldEventClass.deleteEventChild(eventChildId);

      return null;
    }
    return Exception(['找不到对应的事件分类']);
  }

  // 持久化存储
  Future<void> setCache() async {
    final prefs = await SharedPreferences.getInstance();
    final jsonData = countdownEventList.map((e) => e.toJson()).toList();
    await prefs.setString(_cacheKey, jsonEncode(jsonData));
  }

  // 从缓存恢复
  Future<void> getCache() async {
    final prefs = await SharedPreferences.getInstance();
    final cachedData = prefs.getString(_cacheKey);

    if (cachedData == null || cachedData.isEmpty || cachedData == '[]') {
      // 如果缓存无效或为空，且当前列表为空，添加默认分类
      if (countdownEventList.isEmpty) {
        addCountdownEventClass('生活');
        addCountdownEventClass('工作');
        addCountdownEventClass('纪念日');
      }
    } else {
      // 从有效缓存恢复数据
      try {
        final List<dynamic> jsonData = jsonDecode(cachedData);
        final List<CountdownEventClass> restoredList =
            jsonData.map((item) => CountdownEventClass.fromJson(item)).toList();
        countdownEventList.assignAll(restoredList);
      } catch (e) {
        debugPrint('缓存数据解析错误: $e');
      }
    }
  }
}
